import moment from 'moment';

/**
 * 时间戳(秒) 转字符串
 * @param {*} timestamp  时间戳
 */
const timestampToTime = (timestamp,format = "YYYY-MM-DD HH:mm:ss") => {
    var timeObj = moment.unix(timestamp);
    return timeObj.format(format)
};


/**
 * 金额分 转为元
 * @param {*} money  金额分
 */
const moneyShow = (total) => {
    let money = parseInt(total)
    if(money == 0){
        return 0
    }
    let first = Math.ceil(money / 100) 
    let second = money % 100
    if(second == 0) {
        return first
    }
    if(second < 10) {
        return first + '.0' + second
    }
    return first + '.' + second
};


/**
 * 
 * @returns number 当前时间戳 (秒)
 */
const unixTimeStamp = () => {
    return moment().unix()
}

/**
 * 
 * @returns number 当前时间戳 (毫秒)
 */
const unixMSTimeStamp = () => {
    return moment().valueOf()
}

/**
 * 存储localStorage
 */
const setStore = (name, content) => {
    if (!name) return;
    if (typeof content !== 'string') {
        content = JSON.stringify(content);
    }
    window.localStorage.setItem(name, content);
}

/**
 * 获取localStorage
 */
const getStore = name => {
    if (!name) return;
    return window.localStorage.getItem(name);
}

/**
 * 删除localStorage
 */
const removeStore = name => {
    if (!name) return;
    window.localStorage.removeItem(name);
}

/**
 * 设置cookie
 **/
function setCookie(name, value, day) {
    let date = new Date();
    date.setDate(date.getDate() + day);
    document.cookie = name + '=' + value + ';expires=' + date;
};

/**
 * 获取cookie
 **/
function getCookie(name) {
    let reg = RegExp(name + '=([^;]+)');
    let arr = document.cookie.match(reg);
    if (arr) {
        return arr[1];
    } else {
        return '';
    }
};

/**
 * 删除cookie
 **/
function delCookie(name) {
    setCookie(name, null, -1);
};

const arrayFind = (arr,key,val) => {
    if(val == null || key == null || !Array.isArray(arr) && arr.length < 1){
        return -1
    }

    for (let i = 0;i < arr.length; i++) {
        let item = arr[i]
        let keys = Object.keys(item)
        if(keys.includes(key) && (item[key] + "") == (val + "")){
            return i
        }    
    }
    return -1;
}

const arrayFindAll = (arr,key,val) => {
    let res = []
    if(val == null || key == null || !Array.isArray(arr) && arr.length < 1){
        return res
    }

    for (let i = 0;i < arr.length; i++) {
        let item = arr[i]
        let keys = Object.keys(item)
        if(keys.includes(key) && (item[key] + "") == (val + "")){
            res.push(item)
        }    
    }
    return res;
}

const arrayFilterAll = (arr,obj,fnCompare = null) => {
    let res = []
    arr.forEach(item => {
        if(includeSameAttrs(item,obj,fnCompare )){
            res.push(item)
        }
    })
    return res
}

const includeSameAttrs = (source,check ,fnCompare = null) => {
    if(source == null){
        return false
    }
    if(check == null){
        return true
    }
    if(fnCompare == null) {
        fnCompare = (v1,v2) => {
            if(v1 == v2){
                return true
            }
            return false
        }
    }
    let ret = true
    for (const key in check) {
        if (!source.hasOwnProperty(key)) {
            console.log("filter but source not have property of '"+ key +"' source data:" + JSON.stringify(source))
            return false
        }
        let val1 = source[key] + "" //转String 对比字面量
        let val2 = check[key] + "" //转String 对比字面量
        if(!fnCompare(val1,val2)) {
            return false
        }
    }   
    return ret
}

const filterByArray = (val,arr,key = 'id',label = 'name') => {
    if(val == null){
        return 'null'
    }
    if(!Array.isArray(arr)){
        console.log("filterByArray filter arr dataType error arr" + JSON.stringify(arr))
        return ''
    }
    let index = arrayFind(arr,key,val)
    if(index >= 0){
        let item = arr[index]
        let keys = Object.keys(item)
        if(keys.includes(label)){
            return item[label]
        }
    }
    return ''  
}

const arrayColumn = (val,arr) => {
    if(val == null){
        return []
    }
    if(!Array.isArray(arr)){
        console.log("arrayColumn arr dataType error arr" + JSON.stringify(arr))
        return []
    }
    let list = []
    arr.forEach(item => {
        if(item.hasOwnProperty(val)){
            list.push(item[val])
        }
        else{
            list.push(null)
        }
    })    
    return list
}

const arrayUnique = (arr) => {
    if(!Array.isArray(arr)){
        console.log("arrayColumn arr dataType error arr" + JSON.stringify(arr))
        return []
    }
    let res = new Set(arr);
    return [...res]
}

const filterByObject = (val,obj) => {
    if(val == null){
        return 'null'
    }
    if(obj == null){
        return ''
    }
    if(obj.hasOwnProperty(val)){
        return obj[val]
    }
    else{
        console.log("filterByObject object" + JSON.stringify(obj) +" not has Property [" + val + "]")
    }    
    return ''
}

const sleep = (ms) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve()
        }, ms);
    })
}

/**
 * 导出 
 **/
export {
    moneyShow,
    timestampToTime,
    unixTimeStamp,
    unixMSTimeStamp,
    arrayFind,
    arrayFindAll,
    filterByArray,
    filterByObject,    
    arrayFilterAll,
    setStore,
    getStore,
    removeStore,
    setCookie,
    getCookie,
    delCookie,
    arrayColumn,
    arrayUnique,
    sleep,
}